/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa036is.utilities;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jostri
 */
public class DateTimeEditor extends PropertyEditorSupport {

    public static final String DATE_FORMAT = "dd.MM.yyyy HH:mm";

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        
        if (text == null || text.isEmpty()) {
            setValue(null);
        } else {
            SimpleDateFormat sdc = new SimpleDateFormat(DateTimeEditor.DATE_FORMAT);
            try {
                Timestamp ts = new Timestamp(sdc.parse(text).getTime());
                setValue(ts);
            } catch (ParseException ex) {
                Logger.getLogger(DateEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public String getAsText() {
        Timestamp ts = (Timestamp) getValue();
        if (ts == null) {
            return null;
        } else {
            SimpleDateFormat sdc = new SimpleDateFormat(DateEditor.DATE_FORMAT);
            return sdc.format(new Date(ts.getTime()));
        }
    }
}
